package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.entity.ChatMessage;
import com.service.MessageProducer;
import com.service.MessageConsumer;
import com.dao.ChatMessageDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 聊天控制器
 */
@RestController
@RequestMapping("/api/chat")
public class ChatController {

    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Autowired
    private MessageProducer messageProducer;

    @Autowired
    private MessageConsumer messageConsumer;

    @Autowired
    private ChatMessageDao chatMessageDao;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 发送文本消息
     */
    @PostMapping("/send/text")
    public ResponseEntity<Map<String, Object>> sendTextMessage(
            @RequestParam String senderOpenId,
            @RequestParam String receiverOpenId,
            @RequestParam String content) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 参数验证
            if (senderOpenId == null || senderOpenId.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "发送者ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (receiverOpenId == null || receiverOpenId.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "接收者ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (content == null || content.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "消息内容不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 发送消息
            messageProducer.sendTextMessage(senderOpenId, receiverOpenId, content);
            
            response.put("success", true);
            response.put("message", "消息发送成功");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("发送文本消息失败: sender={}, receiver={}, error={}", 
                senderOpenId, receiverOpenId, e.getMessage(), e);
            response.put("success", false);
            response.put("message", "消息发送失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 发送文件消息
     */
    @PostMapping("/send/file")
    public ResponseEntity<Map<String, Object>> sendFileMessage(
            @RequestParam String senderOpenId,
            @RequestParam String receiverOpenId,
            @RequestParam String content,
            @RequestParam String fileUrl,
            @RequestParam String fileName,
            @RequestParam Long fileSize,
            @RequestParam String messageType) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 参数验证
            if (senderOpenId == null || senderOpenId.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "发送者ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (receiverOpenId == null || receiverOpenId.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "接收者ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (fileUrl == null || fileUrl.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "文件URL不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 发送文件消息
            messageProducer.sendFileMessage(senderOpenId, receiverOpenId, content, 
                fileUrl, fileName, fileSize, messageType);
            
            response.put("success", true);
            response.put("message", "文件消息发送成功");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("发送文件消息失败: sender={}, receiver={}, error={}", 
                senderOpenId, receiverOpenId, e.getMessage(), e);
            response.put("success", false);
            response.put("message", "文件消息发送失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取聊天历史记录
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getChatHistory(
            @RequestParam String senderOpenId,
            @RequestParam String receiverOpenId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 创建分页对象
            Page<ChatMessage> pageObj = new Page<>(page, size);
            
            // 构建查询条件
            QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
            queryWrapper.and(wrapper -> 
                wrapper.eq("sender_openid", senderOpenId).eq("receiver_openid", receiverOpenId)
                .or()
                .eq("sender_openid", receiverOpenId).eq("receiver_openid", senderOpenId)
            );
            queryWrapper.orderByDesc("send_time");
            
            // 执行查询
            IPage<ChatMessage> result = chatMessageDao.selectPage(pageObj, queryWrapper);
            
            response.put("success", true);
            response.put("data", result.getRecords());
            response.put("total", result.getTotal());
            response.put("page", result.getCurrent());
            response.put("size", result.getSize());
            
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("获取聊天历史失败: sender={}, receiver={}, error={}", 
                senderOpenId, receiverOpenId, e.getMessage(), e);
            response.put("success", false);
            response.put("message", "获取聊天历史失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/mark-read")
    public ResponseEntity<Map<String, Object>> markMessageAsRead(
            @RequestParam String messageId,
            @RequestParam String readerOpenId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            ChatMessage message = chatMessageDao.selectById(messageId);
            if (message == null) {
                response.put("success", false);
                response.put("message", "消息不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (!readerOpenId.equals(message.getReceiverOpenid())) {
                response.put("success", false);
                response.put("message", "无权限标记此消息为已读");
                return ResponseEntity.badRequest().body(response);
            }
            
            message.setStatus("read");
            message.setReadTime(new java.util.Date());
            chatMessageDao.updateById(message);
            
            response.put("success", true);
            response.put("message", "消息已标记为已读");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("标记消息已读失败: messageId={}, reader={}, error={}", 
                messageId, readerOpenId, e.getMessage(), e);
            response.put("success", false);
            response.put("message", "标记消息已读失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 撤回消息
     */
    @PostMapping("/recall")
    public ResponseEntity<Map<String, Object>> recallMessage(
            @RequestParam String messageId,
            @RequestParam String senderOpenId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            ChatMessage message = chatMessageDao.selectById(messageId);
            if (message == null) {
                response.put("success", false);
                response.put("message", "消息不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (!senderOpenId.equals(message.getSenderOpenid())) {
                response.put("success", false);
                response.put("message", "无权限撤回此消息");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查消息是否超过撤回时间（例如：2分钟内）
            long timeDiff = System.currentTimeMillis() - message.getSendTime().getTime();
            if (timeDiff > 2 * 60 * 1000) { // 2分钟
                response.put("success", false);
                response.put("message", "消息发送超过2分钟，无法撤回");
                return ResponseEntity.badRequest().body(response);
            }
            
            message.setStatus("recalled");
            chatMessageDao.updateById(message);
            
            // 记录撤回信息到Redis
            String recallKey = "recall:" + messageId;
            redisTemplate.opsForValue().set(recallKey, true, 60, TimeUnit.SECONDS);
            
            response.put("success", true);
            response.put("message", "消息已撤回");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("撤回消息失败: messageId={}, sender={}, error={}", 
                messageId, senderOpenId, e.getMessage(), e);
            response.put("success", false);
            response.put("message", "撤回消息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 设置用户在线状态
     */
    @PostMapping("/online")
    public ResponseEntity<Map<String, Object>> setOnlineStatus(
            @RequestParam String openId,
            @RequestParam boolean isOnline) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            messageConsumer.setUserOnlineStatus(openId, isOnline);
            
            response.put("success", true);
            response.put("message", isOnline ? "用户已上线" : "用户已下线");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("设置用户在线状态失败: openId={}, isOnline={}, error={}", 
                openId, isOnline, e.getMessage(), e);
            response.put("success", false);
            response.put("message", "设置在线状态失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * WebSocket消息处理
     */
    @MessageMapping("/chat.sendMessage")
    public void handleMessage(@Payload ChatMessage message, SimpMessageHeaderAccessor headerAccessor) {
        try {
            logger.info("收到WebSocket消息: sender={}, receiver={}, content={}", 
                message.getSenderOpenid(), message.getReceiverOpenid(), message.getContent());
            
            // 发送消息
            messageProducer.sendMessage(message.getReceiverOpenid(), message);
            
        } catch (Exception e) {
            logger.error("处理WebSocket消息失败: {}", e.getMessage(), e);
        }
    }
}
